import React, { PropTypes, Component } from 'react';
import styles from './TreeLikeUI.css';
import withStyles from '../../decorators/withStyles';
import TreeNode from './TreeNode'
import ajax from '../../ajax'

@withStyles(styles)
class TreeLikeUI extends Component {

  constructor () {
    super()

    this.state = {
      nodes: []
    }
  }

  static propTypes = {
    data: React.PropTypes.oneOfType([
      React.PropTypes.string,
      React.PropTypes.array
    ]),
    checkable: React.PropTypes.bool
  }

  static defaultProps = {
    checkable: false
  }

  componentDidMount () {
    if ('array' !== $.type(this.props.data)) {
      ajax({
        url: this.props.data || '/api/resources/menu'
      }).done(resp => {
        if (resp && 0 === resp.code) {
          this._onDataRetrieved(resp.data)
        }
      })
    } else {
      this._onDataRetrieved(this.props.data)
    }
  }

  render() {
    return (
      <ul className="tree-ui">
        {this.state.nodes.length ? this.state.nodes : <div className="load-overlay show"></div>}
      </ul>
    )
  }

  _onDataRetrieved (nodes) {
    let treeNodes = []

    nodes.forEach((item, index) => {
      treeNodes.push(<TreeNode checkable={this.props.checkable} active={!index} data={item} key={item.id} onCKBClick={this.props.onCKBClick}/>)
    })

    this.setState({
      nodes: treeNodes
    })
  }

}

export default TreeLikeUI

